package com.scnu.common.interceptors;


import cn.hutool.core.util.StrUtil;
import com.scnu.common.annotations.NoLogin;
import com.scnu.common.constants.Constant;
import com.scnu.common.domain.dto.PersonalIndexResponse;
import com.scnu.common.domain.po.User;
import com.scnu.common.exception.UnauthorizedException;
import com.scnu.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URI;

@RequiredArgsConstructor
public class UserInfoInterceptor implements HandlerInterceptor {


    private final RestTemplate restTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (hasNoLoginAnnotation(handler)) {
            return true;
        }


        //1.获取登录用户信息
        String token = request.getHeader("Authorization");
        //2.判断是否获取了用户
        if (StrUtil.isNotBlank(token)){


            URI uri = UriComponentsBuilder.fromHttpUrl(Constant.PLATFORM_URL)
                    .queryParam("s", "personal/index")
                    .queryParam("token", token == null ? "" : token)
                    .build(true)
                    .toUri();


            User user;


            try {
                //创建请求头
                HttpHeaders requestHeaders = new HttpHeaders();
                PersonalIndexResponse body;
                HttpEntity<Object> requestEntity = new HttpEntity<>(null, requestHeaders);
                ResponseEntity<PersonalIndexResponse> responseEntity = restTemplate.postForEntity(uri, requestEntity, PersonalIndexResponse.class);
                body = responseEntity.getBody();
                if (body == null || body.getCode() == null || body.getCode() != 0) {
                    throw new UnauthorizedException("登录状态过期，请重新登陆");
                }

                user = body.getData().getUser();

            } catch (RestClientResponseException e) {
                // 服务端返回了非2xx状态码
                // 你可以改用日志记录
                System.err.println("POST失败，status=" + e.getRawStatusCode() + ", body=" + e.getResponseBodyAsString());
                throw e;
            } catch (RestClientException e) {
                System.err.println("POST请求异常: " + e.getMessage());
                throw e;
            }





            UserContext.setUser(user);
        }

        if (UserContext.getUser()== null){
            throw new UnauthorizedException("你的登录状态已失效！");
        }

        return true;
    }

    private boolean hasNoLoginAnnotation(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 检查方法上的注解
            Method method = handlerMethod.getMethod();
            NoLogin methodAnnotation = method.getAnnotation(NoLogin.class);
            if (methodAnnotation != null) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理用户
        UserContext.remove();
    }
}
